<template>
  <div>
    <div style="margin-bottom: 15px">
      <el-button type="primary" style="margin-right: 10px" @click="$router.push('/ruanyue')">返回</el-button>
      <el-input placeholder="请输入内容" style="width: 200px" v-model="params.matName" clearable></el-input>
      <el-button type="warning" style="margin-left: 10px" @click="findBySearch()">查询</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="add()">新增</el-button>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }">
        <el-table-column prop="matName" label="选手姓名" width="200"></el-table-column>
        <el-table-column prop="plagender" label="性别" width="200"></el-table-column>
        <el-table-column prop="plaDepartment" label="部门" width="200"></el-table-column>
        <el-table-column prop="ruaId" label="软约编号" width="170"></el-table-column>
        <!-- <el-table-column prop="plaId" label="选手编号" width="170"></el-table-column> -->
        <!-- <el-table-column prop="matDeclaration" label="参赛宣言" sortable width="200"></el-table-column> -->
        <el-table-column prop="matScore" label="选手分数" sortable width="200"></el-table-column>
        <el-table-column prop="matSequence" sortable label="演讲顺序" width="200">
        <template slot-scope="scope">
          <span v-if="!scope.row.editing" @click="toggleEdit(scope.row)">{{ scope.row.matSequence }}</span>
          <el-input
            v-else
            v-model="scope.row.matSequence"
            @change="updateSequence(scope.row)"
            @blur="toggleEdit(scope.row)"
            placeholder="请输入演讲顺序"
            autocomplete="off"
            style="width: 80%"
            ref="sequenceInput"
          ></el-input>
        </template>
      </el-table-column>
        <!-- <el-table-column prop="matDate" label="创建时间" sortable width="250"></el-table-column> -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger" style="margin-left: 5px">删除</el-button>
            </el-popconfirm> -->
            <el-button type="warning" plain @click="" style="margin-left: 5px">重新计算</el-button>
            <el-button type="success" plain @click="startScore(scope.row)" style="margin-left: 5px">开启评分</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-left: 50%;margin-top: 10px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4"
        :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total"></el-pagination>
    </div>
    <div>
      <!-- Form -->
      <el-dialog title="请填写信息" :visible.sync="dialogFormVisible" width="40%">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="15%" :inline-message="true" style="padding: 20px;">
          <el-form-item label="软约编号" prop="ruaId">
            <el-input v-model="form.ruaId" placeholder="请输入软约编号" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="选手编号" prop="plaId">
            <el-input v-model="form.plaId" placeholder="请输入选手编号" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="选手宣言" prop="matDeclaration">
            <el-input v-model="form.matDeclaration" placeholder="请输入选手宣言" autocomplete="off"
              style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="演讲顺序" prop="matSequence">
            <el-input v-model="form.matSequence" placeholder="请输入演讲顺序" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="选手姓名" prop="matName">
            <el-input v-model="form.matName" placeholder="请输入选手姓名" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Matchscore",
  data() {
    return {
      params: {
        matName: ''
      },
      currentPage4: 1,
      pageSize: 10, // 添加 pageSize 属性
      tableData: [],
      dialogFormVisible: false,
      form: {
        ruaId:'',
        matName: '',
        plagender: '',
        plaDepartment: '',
        matScore: '',
        matSequence: ''
      },
      total: 0, // 添加 total 属性
      jwtToken: localStorage.getItem("user"),
      rules: {
        ruaId: [
          { required: true, message: '请输入软约编号', trigger: 'blur' }
        ],
        plaId: [
          { required: true, message: '请输入选手编号', trigger: 'blur' }
        ],
        matDeclaration: [
          { required: true, message: '请输入选手宣言', trigger: 'blur' }
        ],
        matSequence: [
          { required: true, message: '请输入演讲顺序', trigger: 'blur' }
        ],
        matName: [
          { required: true, message: '请输入选手姓名', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const acid = this.$route.params.acid;
    this.form.ruaId = acid
    this.load();
    this.handleReceivedParams();
    // this.loadAllData(); // 加载所有数据
  },
  onMounted() {


  },
  methods: {
    handleReceivedParams() {
      // 如果您使用的是查询参数
      const queryParam = this.$route.query.someParam; // 替换 someParam 为您实际的参数名称
      if (queryParam) {
        this.form.ruaId = queryParam; // 将接收到的参数赋值给表单的 ruaId
        console.log(queryParam); // 打印接收到的参数
      }
    },
    handleAvatarSuccess(res, file) {
      request.get(`/common/download?name=${res.content}`).then(res => {
        this.form.matAvatar = JSON.parse(res.data).url;
      })
      this.$refs.formRef.validateField("matAvatar");
      this.$forceUpdate();
    },
    load() {
      request.post("/match/list",{
        ruaId: this.form.ruaId,
        page: this.currentPage4,
        size: this.pageSize
      }).then(res => {
        if (res.code === 1) {
          const start = (this.currentPage4 - 1) * this.pageSize;
          const end = start + this.pageSize;
          this.tableData = res.data.slice(start, end).map(item => ({
            ...item,
            editing: false, // 初始化 editing 属性
            originalMatSequence: item.matSequence // 初始化 originalMatSequence 属性
          }));  // 根据页码和每页显示的数量动态截取数据
          this.total = res.data.length > 0 ? res.data[0].total : 0; // 计算总条数
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // load() {
    //   request.post("/match/list", this.form,{
    //     page: this.currentPage4,
    //     size: this.pageSize
    //   }).then(res => {
    //     if (res.code === 1) {
    //       const start = (this.currentPage4 - 1) * this.pageSize;
    //       const end = start + this.pageSize;
    //       this.tableData = res.data.slice(start, end).map(item => ({
    //         ...item,
    //         editing: false, // 初始化 editing 属性
    //         originalMatSequence: item.matSequence // 初始化 originalMatSequence 属性
    //       }));  // 根据页码和每页显示的数量动态截取数据
    //       this.total = res.data.length > 0 ? res.data[0].total : 0; // 计算总条数
    //     } else {
    //       this.$message.error(res.msg);
    //     }
    //   });
    // },



    startScore(row) {
      sessionStorage.setItem('match_current_id', row.id);
      sessionStorage.setItem('match_current_playId', row.plaId);
      sessionStorage.setItem('match_current_matSequence', row.matSequence);
      sessionStorage.setItem('match_current_matName', row.matName);
      this.$router.push("/xsscore").then(() => {
        this.enterFullScreen();
      });
    },
    enterFullScreen() {
      const element = document.documentElement; // 获取整个文档元素
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) { // Firefox
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) { // Chrome, Safari and Opera
        element.webkitRequestFullscreen();
      } else if (element.msRequestFullscreen) { // IE/Edge
        element.msRequestFullscreen();
      }
    },
    add() {
      this.form = {};
      this.dialogFormVisible = true;
    },
    edit(obj) {
      this.form = { ...obj };
      this.dialogFormVisible = true;
    },
    del(id) {
      request.delete(`/match/${id}`).then(res => {
        if (res.code === 1) {
          this.tableData = this.tableData.filter(item => item.id !== id);
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    findBySearch() {
      request.get("/match/page", {
        params: { 
          content: this.params.matName, // 添加查询条件
          page: this.currentPage4, 
          size: this.pageSize 
        },
        headers: {
          'Authorization': `Bearer ${this.jwtToken}`
        }
      }).then(res => {
        if (res.code === 1) {
          this.tableData = res.data.records; // 确保从响应中提取正确的数据
          this.total = res.data.total; // 确保从响应中提取正确的总条数
          this.$message({
            message: '操作成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      });
    },
    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          request.post("/match/save", this.form).then(res => {
            if (res.code === 1) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.load();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage4 = 1; // 切换每页显示数量时，重置为第一页
      this.load();
    },
    handleCurrentChange(val) {
      this.currentPage4 = val;
      this.load();
    },
    formatter(row, column) {
      return row.address;
    },
    // loadAllData() {
    //   request.get("/match/list", {
    //     params: { page: 1, size: 9999 } // 假设最多有9999条数据
    //   }).then(res => {
    //     if (res.code === 1) {
    //       this.allData = res.data; // 假设后端返回的数据直接包含所有记录
    //     } else {
    //       this.$message.error(res.msg);
    //     }
    //   });
    // },
    toggleEdit(row) {
      if (!row.editing) {
        row.originalMatSequence = row.matSequence; // 保存原始序号
      }
      row.editing = !row.editing; // 切换编辑状态
      if (row.editing) {
        this.$nextTick(() => {
          this.$refs.sequenceInput[0].focus(); // 自动聚焦到输入框
        });
      }
    },

    updateSequence(row) {
      const newSequence = row.matSequence;
      const originalSequence = row.originalMatSequence; // 获取原始序号
      const allTableData = this.allData; // 使用全局数据
      const isDuplicate = allTableData.some(item => item.id !== row.id && item.matSequence === newSequence);

      if (isDuplicate) {
        this.$message.error('该序号已存在，请重新输入');
        row.matSequence = originalSequence; // 恢复原始序号
      } else {
        request.post("/match/updateSequence", {
          id: row.id,
          matSequence: newSequence
        }).then(res => {
          if (res.code === 1) {
            this.$message({
              message: '序号更新成功',
              type: 'success'
            });
            row.editing = false; // 关闭编辑状态
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            });
            row.matSequence = originalSequence; // 恢复原始序号
          }
        });
      }
    },
  }
}
</script>

<style scoped>
.el-dialog {
  border-radius: 10px; /* 圆角边框 */
}

.el-form {
  padding: 20px; /* 增加表单内边距 */
}

.el-form-item {
  margin-bottom: 20px; /* 增加表单项之间的间距 */
}

.el-form-item__label {
  font-weight: bold; /* 加粗标签文字 */
}

.el-form-item__content {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}

.el-form-item__error {
  color: red; /* 统一错误提示颜色 */
  font-size: 12px; /* 统一错误提示字体大小 */
  line-height: 1.2; /* 统一错误提示行高 */
  position: absolute; /* 绝对定位，确保错误提示显示在表单项下方 */
  top: 100%; /* 确保错误提示显示在表单项下方 */
  left: 0; /* 左对齐 */
  padding-top: 4px; /* 上边距 */
}

.el-form-item.is-error .el-input__inner {
  border-color: red; /* 输入框错误时的边框颜色 */
}

.el-form-item.is-error .el-select .el-input__inner {
  border-color: red; /* 下拉选择框错误时的边框颜色 */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>